//
//  YWContactViewController.m
//  maintain
//
//  Created by Kyo on 16/5/5.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWContactViewController.h"
#import "UIColor+CustomColors.h"
#import "YWDepartment.h"
#import "YWHandler.h"
#import "YWContactManager.h"
#import "YWContactHeadFooterView.h"
#import "YWContactTableViewCell.h"

#import "PinYin4Objc.h"
#import "pinyin.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"

#define KHeadViewBaseTag 300
@interface YWContactViewController ()<YWContactHeadFooterViewDelegate,YWContactTableViewCellDelegate,UISearchResultsUpdating,UISearchControllerDelegate>{
    UIWebView *phoneCallWebView;
}
@property (nonatomic, strong) NSMutableArray *groupArray;
@property (nonatomic, strong) NSMutableArray *allContacts;

@property (nonatomic, strong) NSMutableArray  *searchList;
@property (nonatomic, strong) UISearchController *searchController;
@end

@implementation YWContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.title.length>0?self.title:NSLocalizedString(@"addressBook", nil);
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.rowHeight = 60.0f;
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchController.searchResultsUpdater = self;
    _searchController.delegate = self;
    _searchController.dimsBackgroundDuringPresentation = NO;
    [_searchController.searchBar sizeToFit];
    
    UIColor *color =  [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1.0];
    _searchController.searchBar.layer.borderWidth = 1;
    _searchController.searchBar.layer.borderColor = [color CGColor];
    _searchController.searchBar.barTintColor = color;
    [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:NSLocalizedString(@"cancel", nil)];
    self.tableView.tableHeaderView = _searchController.searchBar;
}

- (NSMutableArray *)groupArray{
    if (!_groupArray) {
        _allContacts = [NSMutableArray array];
        YWLoginUser *currentUser = [YWLoginTool loginUser];
        NSArray *alldepartment = [[YWContactManager shareManager] departmentWithHandlersByOrganizationNo:currentUser.companyAccount];
        [alldepartment enumerateObjectsUsingBlock:^(YWDepartment*  _Nonnull department, NSUInteger idx, BOOL * _Nonnull stop) {
            [department.memberArray enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
                handler.pinYin = [self nameToPinYinWith:handler.userName?:@""];
                handler.firstLetter = [self namToPinYinFisrtNameWith:handler.userName?:@""];
            }];
            department.memberArray = [self sortWithContacts:department.memberArray];
            [_allContacts addObjectsFromArray:department.memberArray];
        }];
        _groupArray = [NSMutableArray arrayWithArray:alldepartment];
        
    }
    return _groupArray;
}

- (NSArray *)sortWithContacts:(NSArray*)contacts{
    NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"pinYin" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, nil];
    NSArray *sortedArray = [contacts sortedArrayUsingDescriptors:sortDescriptors];
    return sortedArray;
}

#pragma mark - dataSource and delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_searchController.active) {
        return 1;
    }else{
        return self.groupArray.count;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_searchController.active) {
        return [self.searchList count];
    }else{
        YWDepartment *department = self.groupArray[section];
        NSInteger count = department.isOpen ? department.memberArray.count : 0;
        return count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_searchController.active) {
        YWContactTableViewCell *cell = [YWContactTableViewCell cellWithTableView:tableView];
        YWHandler *contact = self.searchList[indexPath.row];
        cell.contact = contact;
        cell.delegate = self;
        return cell;
    }else{
        YWContactTableViewCell *cell = [YWContactTableViewCell cellWithTableView:tableView];
        YWDepartment *department = self.groupArray[indexPath.section];
        cell.contact = department.memberArray[indexPath.row];
        cell.delegate = self;
        return cell;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_searchController.active) {
        return nil;
    }else{
        YWContactHeadFooterView *headView = [YWContactHeadFooterView headerWithTableView:tableView];
        
        headView.delegate = self;
        headView.showOrganizationName = NO;
        headView.department = self.groupArray[section];
        headView.tag = KHeadViewBaseTag + section;
        return headView;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (_searchController.active) {
        return 0.0f;
    }else{
        return 40.0f;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - private method
- (void)clickHeaderView:(YWContactHeadFooterView *)headerView{
    NSInteger tag = headerView.tag - KHeadViewBaseTag;
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:tag] withRowAnimation:UITableViewRowAnimationNone];
}

//搜索时过滤数据
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSString *searchString = searchController.searchBar.text;
    // 谓词的包含语法
    NSMutableArray *searchResults = [_allContacts mutableCopy];
    
    NSMutableArray *andMatchPredicates = [NSMutableArray array];
    
    NSMutableArray *searchItemsPredicate = [NSMutableArray array];
    
    // use NSExpression represent expressions in predicates.
    // NSPredicate is made up of smaller, atomic parts: two NSExpressions (a left-hand value and a right-hand value)
    
    // friendName field matching
    NSExpression *lhs = [NSExpression expressionForKeyPath:@"userName"];
    NSExpression *rhs = [NSExpression expressionForConstantValue:searchString];
    NSPredicate *finalPredicate = [NSComparisonPredicate
                                   predicateWithLeftExpression:lhs
                                   rightExpression:rhs
                                   modifier:NSDirectPredicateModifier
                                   type:NSContainsPredicateOperatorType
                                   options:NSCaseInsensitivePredicateOption];
    [searchItemsPredicate addObject:finalPredicate];
    
    // friendId field matching
    lhs = [NSExpression expressionForKeyPath:@"pinYin"];
    rhs = [NSExpression expressionForConstantValue:searchString];
    finalPredicate = [NSComparisonPredicate
                      predicateWithLeftExpression:lhs
                      rightExpression:rhs
                      modifier:NSDirectPredicateModifier
                      type:NSContainsPredicateOperatorType
                      options:NSCaseInsensitivePredicateOption];
    [searchItemsPredicate addObject:finalPredicate];
    // friendId field matching
    lhs = [NSExpression expressionForKeyPath:@"firstLetter"];
    rhs = [NSExpression expressionForConstantValue:searchString];
    finalPredicate = [NSComparisonPredicate
                      predicateWithLeftExpression:lhs
                      rightExpression:rhs
                      modifier:NSDirectPredicateModifier
                      type:NSContainsPredicateOperatorType
                      options:NSCaseInsensitivePredicateOption];
    [searchItemsPredicate addObject:finalPredicate];
    
    // at this OR predicate to our master AND predicate
    NSCompoundPredicate *orMatchPredicates = [NSCompoundPredicate orPredicateWithSubpredicates:searchItemsPredicate];
    [andMatchPredicates addObject:orMatchPredicates];
    //   }
    
    // match up the fields of the Product object
    NSCompoundPredicate *finalCompoundPredicate =
    [NSCompoundPredicate andPredicateWithSubpredicates:andMatchPredicates];
    if (self.searchList!= nil) {
        [self.searchList removeAllObjects];
    }
    NSMutableArray * searchTemp = [[searchResults filteredArrayUsingPredicate:finalCompoundPredicate] mutableCopy];
    __block NSMutableArray * uniqueIdArray = [NSMutableArray array];
    [searchTemp enumerateObjectsUsingBlock:^(YWHandler *  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        [uniqueIdArray addObject:@(handler.uniqueId)];
    }];
    NSSet *uniqueIdSet = [NSSet setWithArray:uniqueIdArray];
    NSArray * finishSearchArr = [uniqueIdSet allObjects];
    [finishSearchArr enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        YWHandler * handler = [[YWContactManager shareManager] getHandlerWithUniqueId:[obj integerValue]];
        [self.searchList addObject:handler];
    }];
    [self.tableView reloadData];
}

- (void)willPresentSearchController:(UISearchController *)searchController{
    self.navigationController.navigationBar.translucent = YES;
}

- (void)willDismissSearchController:(UISearchController *)searchController{
    self.navigationController.navigationBar.translucent = NO;
}

-(NSString *)nameToPinYinWith:(NSString *)name
{
    HanyuPinyinOutputFormat *outputFormat=[[HanyuPinyinOutputFormat alloc] init];
    [outputFormat setToneType:ToneTypeWithoutTone];
    [outputFormat setVCharType:VCharTypeWithV];
    [outputFormat setCaseType:CaseTypeLowercase];
    NSString *outputPinyin=[PinyinHelper toHanyuPinyinStringWithNSString:name withHanyuPinyinOutputFormat:outputFormat withNSString:@""];
    return outputPinyin;
}

-(NSString *)namToPinYinFisrtNameWith:(NSString *)name
{
    NSString * outputString = @"";
    for (int i =0; i<[name length]; i++) {
        outputString = [NSString stringWithFormat:@"%@%c",outputString,pinyinFirstLetter([name characterAtIndex:i])];
        
    }
    return outputString;
}

#pragma mark - YWContactTableViewCellDelegate
- (void)clickMessageButtonEvent:(YWHandler*)contact{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(@"sendOrNotSendMessage", nil) preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"yes", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *phoneNum =contact.mobile?:@"";
        NSURL *messageURL = [NSURL URLWithString:[NSString stringWithFormat:@"sms://%@",phoneNum]];
        [self sendMessageOrMakeCall:contact url:messageURL];
    }];
    [alert addAction:cancel];
    [alert addAction:ok];
    if (_searchController.active) {
        [_searchController presentViewController:alert animated:YES completion:nil];
    }else{
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)clickPhoneButtonEvent:(YWHandler*)contact{
    NSString *phoneNum =contact.mobile?:@"";
    NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNum]];
    [self sendMessageOrMakeCall:contact url:phoneURL];
}

- (void)sendMessageOrMakeCall:(YWHandler*)contact url:(NSURL *)url{
    if (contact.mobile.length) {
        if ( !phoneCallWebView ) {
            phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];// 这个webView只是一个后台的 不需要add到页面上来  效果跟方法二一样 但是这个方法是合法的
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:url]];
        });
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(@"noPhoneNumber", nil) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"yes", nil) style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancel];
        if (_searchController.active) {
            [_searchController presentViewController:alert animated:YES completion:nil];
        }else{
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
}

- (NSMutableArray*)searchList{
    if (!_searchList) {
        _searchList = [NSMutableArray array];
    }
    return _searchList;
}

- (void)dealloc{
    [_searchController.view removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
